﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

// 在测试项目中
namespace StudentInfoSystem.Tests;

public static class ValidationExtensions
{
    public static bool Validate(object model, out ICollection<ValidationResult> results)
    {
        var context = new ValidationContext(model);
        results = [];
        return Validator.TryValidateObject(model, context, results, true);
    }

    /// <summary>
    /// 打印验证错误集合的详细信息
    /// </summary>
    /// <param name="errors">验证结果集合</param>
    public static void PrintValidationErrors(this IEnumerable<ValidationResult> errors)
    {
        if (errors == null) return;

        var errorList = errors.ToList();
        Console.WriteLine($"发现 {errorList.Count} 个验证错误:");

        foreach (var error in errorList)
        {
            // 获取错误关联的属性名
            var memberNames = error.MemberNames.Any()
                ? string.Join(", ", error.MemberNames)
                : "全局错误";

            Console.WriteLine($"- [{memberNames}]: {error.ErrorMessage}");
        }
    }
}